# -*- coding: utf-8 -*-
##zixue@taobao.com
##2008-6-16

import cgi
import os
import string
import time
import wsgiref.handlers

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import memcache

from AppListDemo import *
from TbApi import *
from HttpClient import HttpClient
from AEProxy import *
from Log import Log
Log.enableDebug = True


config = ApiConfig.all()[0]
Log.info('Fetched ApiConfig from db.')
api = TbApi(config)
api.httpClient = HttpClient(AEHttp())

class TradeBoughtController(webapp.RequestHandler):
	app_path = '/trade/bought'

	def get(self):
		user = checkLogin(self, self.app_path)
		if user is None: return
		rs =  api.getBoughtTrades('title,iid,seller_nick,price,status,num,created,pic_path,item_url,trade_url', user.nickname())
		trades = None
		msg = None
		url = None
		page_redirect =None
		if(rs.isSuccess()):
			trades = rs.rsp
			if(len(trades)>0):
				sellers = ','.join(["%s" %  t.seller_nick.encode('utf-8') for t in trades])
				users_rs = api.getUsers('seller_credit.level', sellers)
				if(users_rs.isSuccess()):
					user_list = users_rs.rsp
					i = 0
					for t in trades:
						t.seller = user_list[i]
						i+=1
		else:
			msg = rs.msg
			if(rs.code == 1004):
				url = getSipLoginUrl(rs.url, self.request.url)
				page_redirect = getPageRedirect(url)
		template_values = {
			'page_header':getPageHeader(user.nickname(),users.create_logout_url(self.app_path)),
			'page_title':'已买到的宝贝',
			'login':user,
			'trades':trades,
			'msg':msg,
			'url':url,
			'page_redirect':page_redirect
		}
		path = os.path.join(os.path.dirname(__file__), 'TradeBought.html')
		self.response.out.write(template.render(path, template_values))

class TradeSoldController(webapp.RequestHandler):
	app_path = '/trade/sold'

	def get(self):
		user = checkLogin(self, self.app_path)
		if user is None: return
		rs =  api.getSoldTrades('title,iid,buyer_nick,price,status,num,created,pic_path,item_url,trade_url', user.nickname())
		trades = None
		msg = None
		url = None
		page_redirect =None
		if(rs.isSuccess()):
			trades = rs.rsp
			if(len(trades)>0):
				users_rs = api.getUsers('buyer_credit.level', ','.join(["%s" %  t.buyer_nick.encode('utf-8') for t in trades]))
				if(users_rs.isSuccess()):
					user_list = users_rs.rsp
					i = 0
					for t in trades:
						t.buyer = user_list[i]
						i+=1
		else:
			msg = rs.msg
			if(rs.code == 1004):
				url = getSipLoginUrl(rs.url, self.request.url)
				page_redirect = getPageRedirect(url)
		template_values = {
			'page_title':'已卖出的宝贝',
			'login':user,
			'trades':trades,
			'msg':msg,
			'url':url,
			'page_redirect':page_redirect,
			'page_header':getPageHeader(user.nickname(),users.create_logout_url(self.app_path))
		}
		path = os.path.join(os.path.dirname(__file__), 'TradeSold.html')
		self.response.out.write(template.render(path, template_values))

def main():
	application = webapp.WSGIApplication(
                                       [(TradeBoughtController.app_path, TradeBoughtController),
				       (TradeSoldController.app_path, TradeSoldController)])
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()